package relu.fbs;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Writer;
import java.text.DecimalFormat;
import java.util.*;

import jfm.model.Farm;
import jfm.model.Output;
import jfm.model.Types.CropType;
import jfm.model.Types.ObjectiveType;
import jfm.model.Types.*;
import relu.fbs.jfm.JFMFarmData;

public class OutputWriter {
	private static DecimalFormat f2 = new DecimalFormat("#00.0");
	private final List<CropType> baseCropTypes;
	private final Writer outputWriter;
	public OutputWriter(Farm base,Writer out){
		baseCropTypes=new ArrayList<CropType>(base.cropping.baseCropTypes());
		outputWriter=out;
	}
	
	void flush() throws IOException {
		outputWriter.flush();
	}
	void close() throws IOException {
		outputWriter.close();
	}
	
	void printHeader() throws IOException {
		StringBuffer lineBuff = new StringBuffer();
		lineBuff.append("farmid,eo,labourUnits,size,totalSetAside,");
		for ( CropType ct: baseCropTypes){
			lineBuff.append(ct+".area,");
		}
		lineBuff.deleteCharAt(lineBuff.length()-1);// Delete last comma				
		outputWriter.write(lineBuff.toString());
		outputWriter.write("\n");
	}
	
	
	void printSolution(JFMFarmData jfm,Farm farm) throws IOException {
		StringBuffer lineBuff = new StringBuffer();
		lineBuff=new StringBuffer(); 	
	//	farm.workers.getWorkers(WorkerType.LABOUR).get(WorkerSubType.LABOUR)
	//	double labArea=farm.workers.getWorkers(WorkerType.LABOUR).get(WorkerSubType.LABOUR).getSolvedArea();
	//	labArea+=farm.workers.getWorkers(WorkerType.LABOUR).get(WorkerSubType.FARMER).getSolvedArea();
		lineBuff.append(jfm.farmId+","+f2.format(farm.getValueForObjective(ObjectiveType.PROFIT))+","+","+f2.format(farm.cropping.getArea())+",");
		lineBuff.append(f2.format(ToJFM.totalSetAside(farm))+",");
		Set<CropType> farmCropTypes=farm.cropping.baseCropTypes();
		for ( CropType ct: baseCropTypes){
			if ( farmCropTypes.contains(ct)){
				lineBuff.append(f2.format(farm.cropping.getCrop(ct).getSolvedArea())+",");
			} else {
				lineBuff.append("0.0,");
			}
		}
		lineBuff.deleteCharAt(lineBuff.length()-1);// Delete last comma		
		outputWriter.write(lineBuff.toString());
		outputWriter.write("\n");
	}

	static void printSummary(Farm farm) throws IOException {
		PrintStream out = System.out;
		out.println("\nPrinting Solution \n"+Output.solution(farm,false));
		out.println(Output.profitSummary(farm,false));
		out.println("Marginals profit summary ");
		out.println(Output.profitSummary(farm,true));
	}
	
	static void printSummary(Farm farm,FileWriter out) throws IOException {				
		out.write("\nPrinting Solution \n"+Output.solution(farm,false));
		out.write(Output.profitSummary(farm,false));
		out.write("Marginals profit summary ");
		out.write(Output.profitSummary(farm,true));
		//			farm.matrix.printCSV("matrix.csv");
//			System.out.println(farm.getAreaForCrop(Types.CropType.WINTERWHEAT));
    }

}
